package org.bigmarketapi.projectreview;

import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Basic.FirstRobot;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Basic.RobotDecorator;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Update.DancingRobotDecorator;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Update.DynamicRobotDecorator;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Update.SingingRobotDecorator;
import org.bigmarketapi.projectreview.DesingMode.DecoratorPattern.Update.basicRobot;
import org.bigmarketapi.projectreview.DesingMode.PipeLineMode.*;
import org.bigmarketapi.projectreview.DesingMode.codeFlow.node;
import org.bigmarketapi.projectreview.DesingMode.strategyMode.ILogicChain;
import org.bigmarketapi.projectreview.DesingMode.strategyMode.factory.logicFactory;
import org.bigmarketapi.projectreview.LUA.LuaService;
import org.bigmarketapi.projectreview.PrefixTree.TreeNode;
import org.bigmarketapi.projectreview.PrefixTree.URLSearch;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ProjectReviewApplication.class)
public class ProjectReviewApplicationTests {
    @Resource
    logicFactory factory;

    @Test
    public void test_logicChain() {
        final ILogicChain logicChain = factory.chainFactory();
        final String str = logicChain.doLogic("hello");
        log.info("str: {}", str);
        String integral = "100积分";
        final String substring = integral.substring(0, integral.indexOf("积分"));
        System.out.println(substring);
    }

    @Test
    public void test_Algorithm() {
        BigDecimal minRate = new BigDecimal("0.00001");
        if (minRate.equals(BigDecimal.ZERO)) {
            System.out.println(1);
        }
        if (minRate.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("minRate cannot be negative");
        }
        // 获取整数部分和小数部分
        String minStr = minRate.toPlainString();
        int start = 0;
        int end = 0;

        // 获取整数部分的位数
        int dotIndex = minStr.indexOf('.');
        if (dotIndex > 0) {
            start = dotIndex;
        } else {
            start = minStr.length();
        }

        System.out.println(minStr.length());
        // 获取小数部分的位数
        if (dotIndex > -1) {
            end = minStr.length() - dotIndex - 1;
        }

        // 如果 minRate 小于 1，则整数部分的位数为 0
        if (minRate.compareTo(BigDecimal.ONE) < 0) {
            start = 0;
        }
        // 返回最终结果
        System.out.println(Math.pow(10, start + end));
    }

    @Test
    public void test_BitSet() {
        String input = "hello world";
        //   String sha256Hash = getSHA256Hash(input);
        final UUID uuid = UUID.nameUUIDFromBytes(input.getBytes());
        final long least = uuid.getLeastSignificantBits();
        final long most = uuid.getMostSignificantBits();
        log.info("uuid:{}", uuid);
        log.info("least:{}", least);
        log.info("most:{}", most);
    }

    private static String getSHA256Hash(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(input.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    public void decoratorBasicTest() {
        new RobotDecorator(new FirstRobot()).doMoreThing();
    }

    @Test
    public void decoratorUpdateTest() {
        final basicRobot basicRobot = new basicRobot();
        DynamicRobotDecorator dynamicRobot = (DynamicRobotDecorator) DynamicRobotDecorator.decorator(basicRobot, new DancingRobotDecorator(basicRobot), new SingingRobotDecorator(basicRobot));
        dynamicRobot.doSomeThing();
    }

    @Resource
    LuaService luaService;
    @Resource
    RedissonClient redisson;

    @Test
    public void test_Dao() {
        luaService.inBatches();
    }

    @Test
    public void test_redis() {
        final RMap<String, Object> map = redisson.getMap("stockMap");
        final Set<String> stringSet = map.keySet();
        System.out.println(stringSet);
    }

    @Test
    public void test_URL() {
        TreeNode a = new TreeNode("a");
        TreeNode b = new TreeNode("b");
        TreeNode c = new TreeNode("c");
        TreeNode d = new TreeNode("d");
        TreeNode e = new TreeNode("e");
        a.setParent(null);
        a.addChild(b);
        b.addChild(c);
        c.addChild(d);
        c.addChild(e);
        final String fullPath = URLSearch.constructFullPath(e);
        log.info("fullPath: {}", fullPath);
        final TreeNode prefix = URLSearch.findNodeWithPrefix(a, "a/b/c/e");
        log.info("prefix: {}", prefix.getPathSegment());
    }

    @Resource
    PipelineRouteConfig routeConfig;

    PipelineExecutor executor;

    @Test
    public void test_prefix_match() {
        final Map<Class<? extends PipelineContext>, List<? extends ContextHandler<? extends PipelineContext>>> pipeHandlerMap = routeConfig.getPipeHandlerMap();
        executor = new PipelineExecutor(pipeHandlerMap);
        executor.accept(new InstanceBuildContext());
    }

    @Test
    public void test_orders_Flow() {
        String orders = "[[Ability1],[Ability3,Ability4,Ability6],[Ability3,Ability9,Ability6],[Ability5]]";
        processOrder(orders);
    }

    public List<List<node>> processOrder(String order) {
        if (order == null) {
            return null;
        }

        // 去除外层方括号
        String innerContent = order.substring(1, order.length() - 1).trim();

        // 使用正则表达式分割内部列表
        String[] parts = innerContent.split("\\],\\[");
        final List<List<node>> lists = Arrays.stream(parts).filter(s -> !s.isEmpty()).map(s -> {
            String part = s.trim();
            if (part.startsWith("[")) {
                part = part.substring(1).trim();
            }
            if (part.endsWith("]")) {
                part = part.substring(0, part.length() - 1).trim();
            }
            return Arrays.stream(part.split(",")).map(str -> new node(str.trim())).toList();
        }).toList();
        log.info("list: {}", JSON.toJSONString(lists));
        // 创建一个列表来存储最终的结果
        List<List<String>> resultLists = new ArrayList<>();
        return lists;
     /*
     // 遍历每个部分并解析
        for (String part : parts) {
            // 去掉每个部分的前后方括号
            part = part.trim();
            if (part.startsWith("[")) {
                part = part.substring(1).trim();
            }
            if (part.endsWith("]")) {
                part = part.substring(0, part.length() - 1).trim();
            }

            // 使用逗号分割每个部分
            String[] elements = part.split(",");
            List<String> currentList = new ArrayList<>();
            for (String element : elements) {
                // 去掉每个元素的前后空格
                element = element.trim();
                currentList.add(element);
            }

            // 将当前列表添加到结果列表中
            resultLists.add(currentList);
        }*/
    }
}
